Home:ALL Converter>Java-Optional versus C++-optional

Java-Optional versus C++-optional

Ask Time:2019-11-04T01:45:59         Author:towi

Json Formatter

Am I right in assuming that the Java-Optional does not have much todo with the C++17-optional?

I know Javas Optional mostly from use in the Stream-API, e.g.:

Optional<Integer> op  = Optional.empty(); 
op.stream().forEach(System.out::println); 

I know it has its uses as a return value as well (not so much as parameter). But concerning this kind of use this is not applicaple to the C++-optional, right?

Or is it "Monads" again, the thing no-one can explain after understanding it? Does the C++-optional have in fact everything to do with Monads, and so have Java-Streams, and thus C++--optional is comparable to Java-Optional? What would be an comparable example, then?

Author:towi,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/58682923/java-optional-versus-c-optional
Tolik Pylypchuk :

Optionals in Java and in C++ (and in a lot of other programming languages) serve a similar purpose - to represent a value that may be present or absent.\n\nOptionals in Java are not only used for streams, they can (and should) be used in their own right. That being said, in Java optionals should be used only as return types of methods that may or may not return a value. The same can be achieved with returning null values, but with that it's much easier to forget to check the returned value. But optionals in Java aren't supposed to just replace every object that may not actually be present (like Maybe in Haskell, for example).\n\nI'm not an expert in C++, but it looks like C++'s optional has largely the same purpose (correct me if I'm wrong).\n\nI won't explain what monads are here, but the concept is quite easy and I really don't know why so many people are afraid of them. If you've read anything about monads, you know that they basically have 2 operations: create a monadic value, and bind it (or flat-map it).\n\nIn Java, Optional.of creates an optional value, and Optional.flatMap, well, flat-maps it. But these operations don't fully respect the monadic laws, so purists claim that optionals in Java are not really monads.\n\nIn C++, you can create an optional using the constructor or the make_optional function, so you have the operation of creation. But I can't find the bind or flat_map function in the standard library. If you wish, you can write one yourself - then if that function respects the monadic laws, the optional will become a monad.",
2019-11-03T18:14:20
yy